<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>context</title>
</head>
<body>
  <div id="root"></div>
  <script src="../js/react.development.js"></script>
  <script src="../js/react-dom.development.js"></script>
  <script src="../js/babel.min.js"></script>
  <script type="text/babel">

    const themes = {
      dark: {
        foreground: '#000',
        background: '#eee'
      },
      light: {
        foreground: '#fff',
        background: '#222'
      }
    }
    // 1. 创建上下文
    const themeContext = React.createContext(themes.dark)

    class ThemeButton extends React.Component {
      // 使用 contextType，来决定使用哪个 Context
      static contextType = themeContext

      render() {
        console.log('themeButton: ', this)
        const { props, context: theme } = this
        return (
          <button {...props} style={{backgroundColor: theme.background, color: theme.foreground}} />
        )
      }
    }

    class Demo extends React.Component {
      state = {
        theme: themes.light
      }

      handleClick = (e) => {
        this.setState({
          theme: this.state.theme === themes.dark ? themes.light : themes.dark
        })
      }
      
      render() {
        return (
          <div>
            <themeContext.Provider value={this.state.theme}>
              <ThemeButton onClick={this.handleClick}>change theme</ThemeButton>   
            </themeContext.Provider> 
          </div>
        )
      }
    }
    ReactDOM.render(<Demo />, document.getElementById('root'))
  </script>
</body>
</html>